/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DNNContentBuilder.Attributes;

namespace DNNContentBuilder.UserControls
{
	/// <summary>
	///	Summary description for FormSearchControl.
	/// </summary>
	[DefaultEvent("RowClicked")]
	public class FormSearchControl : UserControl
	{
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/FormSearchControl";
		private const string resourceengine = "~/DesktopModules/DNNContentBuilder/App_LocalResources/ResourceEngine";

		#region Controls
		protected PlaceHolder plcError;
		protected PlaceHolder plcSearchForm;
		protected PlaceHolder plcFields;
		protected DataList SearchResults;
		protected LinkButton btSearch;
		#endregion

		#region Events
		[Bindable(false)]
		[Browsable(true)]
		[Category("Behavior")]
		public event FormSearchRowClickEventHandler RowClicked;
		#endregion

		#region Member Variables
		private const string COMMAND_SELECT = "Select";
		private readonly Hashtable searchFields = new Hashtable();
		private ContentManagerSettingsInfo cmsInfo = new ContentManagerSettingsInfo();
		private readonly ContentManagerSettingsController cmsController = new ContentManagerSettingsController();
		private readonly FieldDefinitionController fdController = new FieldDefinitionController();
		protected ControlTypeController ctController = new ControlTypeController();
		#endregion

		#region Event Handlers
		private void Page_Load(object sender, EventArgs e)
		{
			cmsInfo = cmsController.GetByModule(ContextUtil.GetModuleId(this));
			
			if (cmsInfo != null) {
				FormDefinitionController formController = new FormDefinitionController();
				FormDefinitionInfo formInfo = formController.GetItem(cmsInfo.FormDefinitionId);
			
				if (formInfo != null) {
					string style = String.Format("<style>{0}</style>", formInfo.CSS);
				
					plcSearchForm.Controls.Add(new LiteralControl(style));	
				}
			}
			
			this.btSearch.Text = Commons.GetLocalizedString("button_Search", resource);

			BuildSearchForm();
		}

		private void btSearch_Click(object sender, EventArgs e)
		{
			ExecuteSearch();
		}

		private void SearchResults_ItemCreated(object sender, DataListItemEventArgs e)
		{
			ImageButton button = (ImageButton)e.Item.FindControl("btSelectRow");

			if (button != null)
			{
				button.Command += button_Command;
			}
		}

		private void SearchResults_ItemDataBound(object sender, DataListItemEventArgs e)
		{
			// TODO: for each DataItem in SearchResults.DataSource, retrieve the corresponding MetaData row and bind it here.
		}

		private void button_Command(object sender, CommandEventArgs e)
		{
			if (e.CommandName == COMMAND_SELECT)
			{
				int metaDataId = GetMetaDataId(e.CommandArgument.ToString());
				OnRowClicked(metaDataId);
			}
		}
		#endregion

		#region Methods
		protected virtual void OnRowClicked(int metaDataId)
		{
			if (this.RowClicked != null)
			{
				this.RowClicked(this, new FormSearchRowClickEventArgs(metaDataId));
			}
		}

		private void BuildSearchForm()
		{
			int moduleId = ContextUtil.GetModuleId(this);

			if (moduleId != Null.NullInteger)
			{
				cmsInfo = cmsController.GetByModule(moduleId);

				if (cmsInfo == null)
				{
					// Notify the user that corrective action is needed
					ErrorProvider.AddErrorMessage(plcError, "ERR_FORM_NOT_REGISTERED", resource);
					
					// Hide the main controls
					plcSearchForm.Visible = false;
					
					return;
				}

				ArrayList fields = fdController.GetByFormDefinition(cmsInfo.FormDefinitionId);

				foreach (FieldDefinitionInfo fdInfo in fields)
				{
					ProcessField(fdInfo);
				}
			}
		}

		/// <summary>
		/// If the field is marked as a search field, is visible, and 
		/// is not a primary key field, add it to the output stream.
		/// If the field is a primary key field, add it to the <see cref="searchFields"/>
		/// Hashtable with a PK identifier.
		/// </summary>
		/// <param name="fdInfo"></param>
		private void ProcessField(FieldDefinitionInfo fdInfo)
		{
			#region Add the field as PK or output it to the response stream
			if (fdInfo.IsPrimaryKey)
			{
				this.searchFields.Add(fdInfo.SourceField.Split('.')[0] + ".PK", fdInfo.SourceField);
			}
			else
			{
				if (fdInfo.Search && fdInfo.Visible)
				{
					this.RenderControl(fdInfo);
				}
			}
			#endregion
		}

		/// <summary>
		/// Renders a user control that implements the <see cref="IFormlet"/>
		/// interface in a user specified manner.
		/// </summary>
		/// <param name="fdInfo"></param>
		private void RenderControl(FieldDefinitionInfo fdInfo)
		{
			ControlTypeInfo ctInfo = ctController.GetItem(fdInfo.ControlTypeId);
					
			string controlPath  = Page.ResolveUrl("~/" + ctInfo.ControlPath).Replace("Def.", "Control.");
			UserControl formlet = (UserControl)Page.LoadControl(controlPath);

			Type t = formlet.GetType();

			if (!t.IsDefined(typeof(FormEngineSearchControlAttribute), true))
			{
				throw new ApplicationException(String.Format(Commons.GetLocalizedString("MISSING_FormEngineSearchControlAttribute", resourceengine), controlPath));
			}

			FormEngineSearchControlAttribute[] myAttributes = 
				(FormEngineSearchControlAttribute[])t.GetCustomAttributes(
				typeof(FormEngineSearchControlAttribute), true);

			// We are only interested in the first occurrence anyway
			Debug.Assert(myAttributes.Length > 0);

			FormEngineSearchControlAttribute fesca = myAttributes[0];

			UserControl theControl = (UserControl)Page.LoadControl(fesca.ControlPath);

			if (theControl is ISearchControl)
			{
				string xml = Commons.InsertChildNode("<CssClass>" + fdInfo.CssClass + "</CssClass>", fdInfo.XML);

				((ISearchControl)theControl).SetConfig(xml);
			}

			plcFields.Controls.Add(new LiteralControl("<tr><td>"));
			plcFields.Controls.Add(new LiteralControl(fdInfo.Title));
			plcFields.Controls.Add(new LiteralControl("</td>"));

			plcFields.Controls.Add(new LiteralControl("<td>"));
			plcFields.Controls.Add(theControl);
			plcFields.Controls.Add(new LiteralControl("</td></tr>"));

			this.searchFields.Add(fdInfo.SourceField, theControl);
		}

		/// <summary>
		/// Performs the actual search using the search criteria specified 
		/// by the user in the search form.
		/// </summary>
		private void ExecuteSearch()
		{
			if (cmsInfo == null)
			{
				cmsInfo = cmsController.GetByModule(ContextUtil.GetModuleId(this));			
			}

			int id = cmsInfo.FormDefinitionId;

			MasterSearchController searchController = new MasterSearchController(id, searchFields);

			SearchResults.DataSource = searchController.GetByUserCriteria();
			SearchResults.DataBind();
		}

		/// <summary>
		/// Extracts the metadata Id for the command
		/// </summary>
		/// <param name="commandArgument"></param>
		/// <returns></returns>
		private static int GetMetaDataId(string commandArgument)
		{
			int result = Null.NullInteger;

			if (commandArgument != null)
			{
				try
				{
					result = Int32.Parse(commandArgument);
				}
				catch (FormatException)
				{
					// return Null.NullInteger
				}
			}

			return result;
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.btSearch.Click += new System.EventHandler(this.btSearch_Click);
			this.SearchResults.ItemCreated += new System.Web.UI.WebControls.DataListItemEventHandler(this.SearchResults_ItemCreated);
			this.SearchResults.ItemDataBound += new DataListItemEventHandler(SearchResults_ItemDataBound);

		}
		#endregion
	}
}
